package com.cbank.platform.interceptor;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.http.util.TextUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.cbank.controller.web.WebUserController;
import com.cbank.service.UserService;
import com.cbank.utils.CookieUtils;
import com.cbank.utils.StringUtil;

import java.io.IOException;

public class AuthInterceptor extends HandlerInterceptorAdapter {
	@Autowired
	private UserService userService;
	Logger logger = Logger.getLogger(AuthInterceptor.class);
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
		String uid = CookieUtils.getCookieValue(request, WebUserController.COOKIE_UID);
		String token = CookieUtils.getCookieValue(request, WebUserController.COOKIE_TOKEN);
		logger.info("------------uid:"+uid+",token:"+token);
		if (TextUtils.isBlank(uid) || userIsNull(uid,token)) {// uid为空或uid取出的user为空
			response.sendRedirect("/web/user/login");
			return false;
		}
		return true;
	}

	/**
	 * 验证uid 为null返回true
	 * 
	 * @param uid
	 * @return
	 */
	public boolean userIsNull(String uid,String token) {
		return userService.getByViewIdAndToken(StringUtil.toLongValue(uid),token) == null;
	}
}
